package main

/**
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

解析:
	回溯+分治法
	借助栈进行回溯
*/

func pathSum(root *TreeNode, sum int) [][]int {
	res := [][]int{}
	list := []int{}
	var helper func(root *TreeNode, sum int, res *[][]int, list *[]int)
	helper = func(root *TreeNode, sum int, res *[][]int, list *[]int) {
		if root == nil {
			return
		}
		*list = append(*list, root.Val)
		if sum == root.Val && root.Left == nil && root.Right == nil {
			*res = append(*res, *list)
			*list = (*list)[:len(*list)-1]
			return
		}

		sum = sum - root.Val
		helper(root.Left, sum, res, list)
		helper(root.Right, sum, res, list)

	}
	helper(root, sum, &res, &list)

	return res
}
